﻿using Farming.Application.Traceabilities.Dtos;
using Farming.Domain.Entities;
using Farming.Repositories;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Panda.DynamicWebApi;
using Panda.DynamicWebApi.Attributes;
using QRCoder;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace Farming.Application.Traceabilities
{
    [DynamicWebApi]
    [ApiExplorerSettings(GroupName = "v1")]

    public class TraceabilityDataService : IDynamicWebApi, ITraceabilityDataService
    {
        private readonly IRepository<Traceability> traceabilityRep;
        private readonly IConfiguration configuration;
        private readonly IWebHostEnvironment webHostEnvironment;
        public TraceabilityDataService(IRepository<Traceability> traceabilityRep, IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
        {
            this.traceabilityRep = traceabilityRep;
            this.configuration = configuration;
            this.webHostEnvironment = webHostEnvironment;
        }
        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> Upload(IFormFile file)
        {
            string fileName = file.FileName;
            var path = Directory.GetCurrentDirectory() + @"\wwwroot\img\" + fileName;
            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                file.CopyTo(fs);
                fs.Flush();
            }
            return ("http://localhost:13796/img/" + fileName);
        }
        [HttpPost]
        public async Task<string> UploadFile(IFormFile file)
        {
            var extfiles = configuration["AllowFile"].Split("|");
            var efile = Path.GetExtension(file.FileName);
            if (!extfiles.Contains(efile))
            {
                throw new Exception("文件类型错误");
            }
            if (file.Length / 1024 > 100)
            {
                throw new Exception("文件过大！！！");
            }
            var dicPath = $"/Image/{DateTime.Now.ToString("yyyy")}/{DateTime.Now.ToString("yyyyMMdd")}";
            if (!Directory.Exists($"{webHostEnvironment.WebRootPath}{dicPath}"))
            {
                Directory.CreateDirectory($"{webHostEnvironment.WebRootPath}{dicPath}");
            }

            Random random = new Random();
            var newFileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssfff")}_{random.Next(100, 999)}{efile}";
            using (FileStream fs = new FileStream($"{webHostEnvironment.WebRootPath}{dicPath}/{newFileName}", FileMode.Create))
            {
                await file.CopyToAsync(fs);
            }
            var path = $"{dicPath}{newFileName}";
            return path;

        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="traceability"></param>
        /// <returns></returns>
        public async Task<int> AddTraceability(Traceability traceability)
        {
            int n = await traceabilityRep.AddAsync(traceability);
            return n;

        }
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public async Task<IList<Traceability>> GetTraceabilities()
        {
            return await traceabilityRep.GetAllAsync();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<int> DelTraceabilitity(int id)
        {
            DelTasDto delTasDto = new DelTasDto();
            var res = await traceabilityRep.GetByIdAsync(x => x.TraceabilityId == id);
            res.IsDel = true;
            res.DelTime = DateTime.Now;
            res.DelById = delTasDto.DelById;
            res.DelByName = delTasDto.DelByName;
            int n = await traceabilityRep.UpdAsync(res);
            return n;
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="tas"></param>
        /// <returns>返回受影响行数</returns>                                                                                                                                                  
        public async Task<int> UpdTraceabilitity(UpdTasDto tas)
        {
            var res = await traceabilityRep.GetByIdAsync(x => x.TraceabilityId == tas.TraceabilityId);
            res.GoodName = tas.GoodName;
            res.Production = tas.Production;
            res.ExpirationDay = tas.ExpirationDay;
            res.ProductionNumber = tas.ProductionNumber;
            res.ProductionFirm = tas.ProductionFirm;
            res.InfoIntegrity = tas.InfoIntegrity;
            res.TraceabilityImg = tas.TraceabilityImg;
            res.UpdById = tas.UpdById;
            res.UpdByName = tas.UpdByName;
            res.UpdTime = DateTime.Now;
            return await traceabilityRep.UpdAsync(res);
        }
        public async Task<Traceability> GetTasInfo(int id)
        {
            var list = await traceabilityRep.GetByIdAsync(x => x.TraceabilityId == id);
            return list;
        }



    }
}
